package utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import net.sf.json.JSONObject;
import play.Logger;
import play.libs.WS;
import play.libs.WS.HttpResponse;
import play.libs.WS.WSRequest;

public class WSUtil {
    
    public static JsonObject post(String url,String sid, String token,Map<String,String> params){
        String timeStamp = UrlUtil.generateTimestamp();
        String sign = UrlUtil.generateSignature(sid, timeStamp, token);
        JsonObject result = new JsonObject();
        params.put("sid", sid);
        params.put("token",token);
        params.put("time",timeStamp);
        params.put("sign", sign);
        try {
            HttpResponse resp = WS.url(url).setParameters(params).postAsync().get();
            JsonElement _json = resp.getJson();
            if(_json.isJsonObject()){
               result = _json.getAsJsonObject();
               result = result.get("resp").getAsJsonObject();
            }
        } catch (InterruptedException | ExecutionException e) {
            Logger.error("[%s]: url<%s>, sid<%s>, token<%s>, params<%s>","POST",url,sid,token,params);
        }
        return result;
        
    }
    
    public static JsonObject httpsPost(String url,String sid,String token,String body){
        String timestamp = UrlUtil.generateSignTimestamp();
        String sigParameter = UrlUtil.generateSigParameter(sid, token, timestamp);
        String authorization = UrlUtil.generateAuthorization(sid, timestamp);
        url = url.replace("{sid}", sid);
        WSRequest req = WS.url(url+"?sig="+sigParameter);
        req.setHeader("Accept", "application/json");
        req.setHeader("Content-Type", "application/json;charset=utf-8");
        req.setHeader("Authorization", authorization);
        req.body=body;
        System.out.println("body==="+body);
        JsonObject result = new JsonObject();
        try {
            HttpResponse resp = req.postAsync().get();
            JsonElement _json = resp.getJson();
            if(_json.isJsonObject()){
                result = _json.getAsJsonObject();
                result = result.get("resp").getAsJsonObject();
             }
        } catch (InterruptedException | ExecutionException e) {
             Logger.error("[%s]: url<%s>, sid<%s>, token<%s>, body<%s>","httpsPost",url,sid,token,body);
        }
        return result;
    }

    public static String uploadFile(String url,String sid,String token,String appId,File file){
        String timestamp = UrlUtil.generateTimestamp();
        String sign = UrlUtil.generateSignature(sid, timestamp, token);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .addPart("sid", new StringBody(sid,ContentType.create("text/plain")))
                .addPart("token",new StringBody(token,ContentType.create("text/plain")))
                .addPart("time",new StringBody(timestamp,ContentType.create("text/plain")))
                .addPart("appId",new StringBody(appId,ContentType.create("text/plain")))
                .addPart("sign",new StringBody(sign,ContentType.create("text/plain")))
                .addBinaryBody("file", file)
                .build();
        httpPost.setEntity(reqEntity);
        CloseableHttpResponse resp = null;
        String result = "";
        try {
            resp = httpclient.execute(httpPost);
            HttpEntity respEntity = resp.getEntity();
            if(respEntity!=null){
              result =  EntityUtils.toString(respEntity,"utf-8");
            }
            EntityUtils.consume(respEntity);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                resp.close();
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }   
        return result;
    }

    
    
  }
